<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>006 千分号</title>
</head>
<body>

  <h1>006 千分号</h1>
  <p>数字逢千位加逗号分隔</p>
  <p>如 "10000000000" 处理为 "10,000,000,000"，而 "100" 则不处理</p>

  <form id="myform" method="get">
    <input type="text" name="num" value="10000000000" placeholder="请随机输入数字...">
    <input type="submit" value="走你">
  </form>

  <script>
    document.getElementById("myform").addEventListener("submit", function(e) {

      //阻止默认提交行为.
      e.preventDefault();

      var num = this.num.value;
      var result = "";

      //为空验证.
      if( num == "" ) { return; }
      //数字验证
      if( /\D+/.test(num) ) { return; }

      //因为从右开始三位加逗号，所以字符串倒序处理.
      result = num.split("").reverse().join("").replace(/(\d{3}\B)/g, "$1,");
      //把处理完的倒序字符串还原.
      result = result.split("").reverse().join("");

      alert(result);

    }, false);
  </script>

</body>
</html>
